<template>
  <div class="set-params" @click="($event) => $event.stopPropagation()">
    <!--  body  -->
    <div class="description">
      <div class="prompt-message">请输入"$"选择数据表</div>
      <a-spin :spinning="!excuteIsComplete" tip="Loading...">
        <!-- 编辑器 -->
        <code-mirror-editor
          v-if="isShowOperatorParameter"
          mode="text/x-sql"
          :value="sql"
          :height="'255'"
          :from="'etlSql'"
          :table-list="_linkedTableList"
          @update:value="updateValue"
        ></code-mirror-editor>
      </a-spin>
    </div>
    <!--  footer  -->
    <div class="footer-buttons">
      <div class="btn import-btn" @click="confirm">确定</div>
      <div class="btn cancel-btn" @click="cancelChange">取消</div>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import DataViewStore from '@/store/modules/dataview'
import { Watch } from 'vue-property-decorator'
import { cloneDeep } from 'lodash'
import CodeMirrorEditor from '@/components/studio/data/popup/CodeMirrorEditor.vue'

@Component({
  components: {
    CodeMirrorEditor,
  },
})
export default class EtlSql extends Vue {
  // sql 语句
  public sql: string = ''

  private get selectNode() {
    return DataViewStore.selectNode
  }

  public get isShowOperatorParameter() {
    return DataViewStore.isShowOperatorParameter
  }

  // execute 执行完毕才可编辑，否则内容会被清空
  public get excuteIsComplete() {
    return (
      DataViewStore.selectNode?.data?.lastStatus ??
      DataViewStore.executionCompletionType
    )
  }

  // 监听激活的节点
  @Watch('selectNode', { deep: true })
  private changeSelectNode(selectNode: any) {
    if (selectNode) {
      this.initSet()
      DataViewStore.getTableList()
    }
  }

  // 节点 列表
  private get operatorNodes() {
    return DataViewStore.pipelineNodes
  }

  // 监听 pipeline 节点变化, 更改input table list
  @Watch('operatorNodes', { deep: true })
  private handlePipelineChange() {
    DataViewStore.getTableList()
  }

  //  更新cell代码的值
  public updateValue(value: string) {
    this.sql = value
  }

  public get _linkedTableList(): any {
    return DataViewStore.LinkedTableList
  }

  /**
   * Vue 组件生命周期 created
   */
  public created() {
    this.initSet()
    DataViewStore.getTableList()
  }

  public initSet() {
    this.sql = cloneDeep(this.selectNode.data.sql)
  }

  /**
   * 确认
   */
  public confirm() {
    this.$emit('confirm', { sql: this.sql })
  }

  /**
   * 取消修改
   */
  public cancelChange() {
    this.initSet()
    this.$emit('cancel')
  }
}
</script>

<style lang="less" scoped>
@import '@/components/studio/data/set-params/setParams';

.prompt-message {
  margin-bottom: 12px;
}
</style>
